package com.tuling.netty.splitpacket;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

//自定义解码器
public class MyMessageDecode extends ByteToMessageDecoder {

    int length = 0;
    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
//        System.out.println("解码其被调用:"+new String(byteBuf.array(),0,byteBuf.readableBytes()));
        System.out.println("解码器被调用@！");
        System.out.println(byteBuf);
        System.out.println("字节长度"+byteBuf.readableBytes());
        if (byteBuf.readableBytes() > 4) {
            if(length == 0){
               length = byteBuf.readInt();
            }
            if(byteBuf.readableBytes() < length){
                System.out.println("可以读取的数据长度不够请继续等待！");
                return;
            }
            byte[] content = new byte[length];
            if(byteBuf.readableBytes() >= length){
                byteBuf.readBytes(content);

                MyMessagePropol propol = new MyMessagePropol();
                propol.setLen(length);
                propol.setContent(content);
                list.add(propol);
            }

        }
        length = 0;
    }
}
